import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import TitleNameCpn from '@/components/TitleNameCpn';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Tag, Tooltip } from 'antd';
import { useRef, useState } from 'react';
import { querySystemWarning, removeSystemWarningRule } from '../service';
import type { SystemWarningRuleTableItem } from '../typings.d';
import CreateRule from './components/CreateRule';
import UpdateRuleModal from './components/UpdateRule';

const SystemWarningList = () => {
  const [currRule, setCurrRule] = useState<SystemWarningRuleTableItem | null>(null);
  const [visible, setVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<SystemWarningRuleTableItem>[] = [
    {
      title: 'id',
      hideInSearch: true,
      hideInTable: true,
      dataIndex: '_id',
    },
    {
      title: '规则名称',
      dataIndex: 'name',
      render: (_, record) => <TitleNameCpn title={record.name} desc={record.description} />,
    },
    {
      title: '是否启用',
      dataIndex: 'enable',
      width: 80,
      align: 'center',
      valueEnum: {
        true: { text: '启用', status: 'success' },
        false: { text: '未启用', status: 'error' },
      },
    },
    {
      title: '生效时间',
      dataIndex: 'effectiveTime',
      width: 120,
      hideInSearch: true,
      align: 'center',
      render: (_, record) =>
        record?.effectiveTime && <span>{record.effectiveTime.join(' ~ ')}点</span>,
    },
    {
      title: '推送间隔',
      width: 80,
      dataIndex: 'interval',
      hideInSearch: true,
      align: 'center',
      render: (text) => (text ? `${text}分钟` : '-'),
    },
    {
      title: '钉钉机器人',
      dataIndex: 'ding',
      align: 'center',
      width: 120,
      hideInSearch: true,
      render: (_, record) =>
        record.ding && record?.ding.length > 0 ? (
          record?.ding.map((item) => <Tag key={item}>{item}</Tag>)
        ) : (
          <PlaceHolderCpn text="暂无相关配置" />
        ),
    },
    {
      title: '通知目标手机号',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'dingTargetPhones',
      render: (_, record) => {
        const targetText = record.dingTargetPhones && record.dingTargetPhones.join(',');
        return record.dingTargetPhones && record.dingTargetPhones.length > 0 ? (
          <Tooltip title={targetText}>
            <p
              style={{
                fontSize: '12px',
                margin: 0,
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                overflow: 'hidden',
                width: '100%',
              }}
            >
              {targetText}
            </p>
          </Tooltip>
        ) : (
          <PlaceHolderCpn text="暂无相关数据" />
        );
      },
    },
    {
      title: '生效用户',
      dataIndex: 'appliedUsers',
      width: 300,
      hideInSearch: true,
      render: (_, record) =>
        record.appliedUsers && record?.appliedUsers.length > 0 ? (
          record?.appliedUsers.map((item) => <Tag key={item}>{item}</Tag>)
        ) : (
          <PlaceHolderCpn text="暂无相关配置" />
        ),
    },
    {
      title: '创建时间',
      width: 180,
      dataIndex: 'createTime',
      align: 'center',
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      key: 'option',
      width: 100,
      align: 'center',
      valueType: 'option',
      fixed: 'right',
      render: (text, record, x, action) => [
        <a
          key={record._id}
          onClick={() => {
            setCurrRule(record);
            setVisible(true);
          }}
        >
          编辑
        </a>,
        <ConfirmModal
          key={record._id}
          reload={() => action?.reload()}
          operFunc={async () => await removeSystemWarningRule(record._id)}
          text={`确认要删除告警规则 ${record.name} 吗？`}
        />,
      ],
    },
  ];

  return (
    <PageHeaderWrapper
      title={false}
      subTitle="告警规则列表; 流量卡告警通知请编辑或添加名为「流量卡告警」的相关规则(注:流量卡告警将无视时间段和间隔配置，固定在每日九点进行推送)"
    >
      <ProTable<SystemWarningRuleTableItem>
        rowKey="_id"
        columns={columns}
        actionRef={actionRef}
        scroll={{ x: true }}
        search={{ labelWidth: 'auto' }}
        style={{ whiteSpace: 'nowrap' }}
        pagination={{
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        request={async (params, sort) => querySystemWarning(params, sort)}
        toolBarRender={(action) => [<CreateRule key="_id" reload={() => action?.reload()} />]}
      />
      {visible && currRule && (
        <UpdateRuleModal
          visible={visible}
          setUnvisible={() => {
            setCurrRule(null);
            setVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
          warningRule={currRule}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default SystemWarningList;
